﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using YouDown.Models;
using System.Web;
using System.Web.Script.Serialization;

namespace YouDown
{
    public class Procesor
    {
        public static Video Process(Video vid)
        {
            string page;

            try { page = GetContent(vid.Address); }
            catch (WebException ex)
            {
                vid.Error = ex.Message;
                return vid;
            }

            vid = Catch(page, vid);

            return vid;
        }

        internal static Video Catch(string page, Video vid)
        {
            Match m = Regex.Match(page, @"var swfArgs = (.+);");

            if (m.Success && m.Groups.Count >= 2)
            {
                string match = m.Groups[1].Value;

                var data = new JavaScriptSerializer().Deserialize<SwfArgs>(match);
                vid.L = data.l;
                vid.T = data.t;

                Match title = Regex.Match(page, "<title>YouTube - (.+)</title>");
                if (title.Success)
                {
                    vid.Title = title.Groups[1].Value.Trim();
                }
                else
                {
                    vid.Title = vid.Id;
                }
            }
            else
            {
                Match err = Regex.Match(page, "<div id=\"error-box\" class=\"errorBox\">([^']*?)</div>");

                if (err.Success)
                {
                    vid.Error = err.Groups[1].Value.Trim();
                }
                else
                {
                    vid.Error = "Can't parse page";
                }
            }

            return vid;
        }

        internal static string GetContent(Uri url)
        {
            string buffer;

            var req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "GET";

            var resp = (HttpWebResponse)req.GetResponse();
            var sr = new StreamReader(resp.GetResponseStream());
            buffer = sr.ReadToEnd();
            sr.Close();

            return (buffer);
        }

        public class SwfArgs
        {
            public SwfArgs() { }
            public int l { get; set; }
            public string t { get; set; }
        }
    }
}